package ac.st.server;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class STeditor {

	public static final String NUMBER_REGEX = "^[0-9]{1,5}$";
	public static final String separator = " --> ";
	
	public static final String TIME_STAMP_REGEX = "\\b([0-9:,]{12})\\b";
	
	public static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss,SSS");
	
	
	private static STeditor instance;

	public static STeditor getInstance() {
		if (instance == null) {
			instance = new STeditor();
			
		}
		return instance;
	}
	
	public boolean matchNumber(String data){
		return Pattern.compile(NUMBER_REGEX).matcher(data).matches();
	}
	
	public String extractDate(String line, boolean first){
		Matcher m = Pattern.compile(TIME_STAMP_REGEX).matcher(line);
		int id = first ? 0 : 1;
		if(m.find(id)){
			return m.group(0);
		} else {
			return "";
		}		
	}
	
	public String processTimeStampLine(String line, String shift, boolean add) throws ParseException{
		return processTimeStamp(extractDate(line, true), shift, add) + separator + processTimeStamp(extractDate(line, false), shift, add);
	}
	
	public String processTimeStamp(String timeStamp, String shift, boolean add) throws ParseException{
		
		Date sourceDate = dateFormat.parse(timeStamp);
		Date shiftDate = dateFormat.parse(shift);
		Calendar c = Calendar.getInstance();
		c.setTime(shiftDate);
		int sec = c.get(Calendar.SECOND);
		int millisec = c.get(Calendar.MILLISECOND);
		if(!add){
			sec = 0 - sec;
			millisec = 0 - millisec;
		}
		c.setTime(sourceDate);
		c.add(Calendar.SECOND, sec);
		c.add(Calendar.MILLISECOND, millisec);
		return dateFormat.format(c.getTime());
	}
	
	public String process(String data, String shift, boolean add){
		StringBuilder builder = new StringBuilder();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data.getBytes("UTF-8"))));
			String line;
			while((line = reader.readLine()) != null){
				builder.append(line).append("\n");
				if(matchNumber(line)){
					builder.append(processTimeStampLine(reader.readLine(), shift, add)).append("\n");
				}
			}			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return builder.toString();
	}
	
	
	
}
